package com.qf.controller;

import com.qf.pojo.R;
import com.qf.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;

//@RestController
//@RequestMapping("/user")
public class UserController2 {

    @Autowired
    UserService userService;

    @Autowired
    private RestTemplate restTemplate;

    //服务发现客户端
    @Autowired
    private DiscoveryClient discoveryClient;

    private AtomicInteger ai = new AtomicInteger(0);

    @GetMapping("/{id}")
    public R findOrders(@PathVariable("id") Integer id) throws InterruptedException {

        //基于服务名称，发现指定名称的服务
        List<ServiceInstance> instances = discoveryClient.getInstances("QF-ORDER");

        //模拟随机负载均衡
        //[0,instances.size())
//        int idx = new Random().nextInt(instances.size());

        //模拟轮询策略
        int count = ai.incrementAndGet();
        int idx = count % instances.size();

        ServiceInstance orderInstance = instances.get(idx);
        String ip = orderInstance.getHost();
        int port = orderInstance.getPort();


        //利用restTemplate发送http请求，访问order服务的数据
        R r = restTemplate.getForObject("http://"+ip+":"+port+"/order/" + id, R.class);

        return r;
    }
}
